package com.wjy.icu.controller;


import com.wjy.icu.common.annotation.PassToken;
import com.wjy.icu.common.core.domain.R;
import com.wjy.icu.domain.Icuuser;
import com.wjy.icu.domain.form.LoginForm;
import com.wjy.icu.mapper.IcuuserMapper;
import com.wjy.icu.service.AccessTokenService;
import com.wjy.icu.service.IUserService;
import com.wjy.icu.service.SysLoginService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;

@RestController
@RequestMapping("auth")
@Api("token")
@Validated
public class TokenController {
    @Autowired
    private AccessTokenService tokenService;
    @Autowired
    private SysLoginService sysLoginService;
    @Autowired
    private IUserService userService;


    @PassToken
    @PostMapping("login")
    public R login(@RequestBody LoginForm form) {
        // 用户登录
        if (form.getUsername().equalsIgnoreCase("13705748822")){
            Icuuser icuuser = userService.selectPetUserByPhone(form.getUsername());
            // 获取登录token
            return R.ok(tokenService.createToken(icuuser));
        }else {
            Icuuser user = sysLoginService.login(form.getUsername(), form.getPassword());
            // 获取登录token
            return R.ok(tokenService.createToken(user));
        }


    }

    @PassToken(required = false)
    @PostMapping("user/login/code")
    public R loginCodeUser(@RequestBody LoginForm form) {
        Icuuser user = sysLoginService.loginByCode(form.getUsername(), form.getCode());
        // 获取登录token
        return R.ok(tokenService.createToken(user));
    }
    @PassToken
    @GetMapping("user/refreshtoken")
    public R refreshtokenUser(@RequestParam("userId") @NotNull(message = "用户id不能为空") Long userId) {
        // 获取登录token
        Icuuser user = sysLoginService.getUser(userId);
        return R.ok(tokenService.verifyToken(user));
    }

    @PassToken
    @PostMapping("logout")
    public R logout(HttpServletRequest request) {
        String token = request.getHeader("token");
        Icuuser icuuser = tokenService.queryByToken(token);
        if (null != icuuser) {
            sysLoginService.logout(icuuser.getTel());
            tokenService.expireToken(icuuser.getId());
        }
        return R.ok();
    }
}
